import { useEffect, useState } from "react";
import axios from '../utils/axios';
import { toast } from "sonner";
import { useNavigate } from 'react-router-dom';
import { ethers } from "ethers";


const InsuranceManage = () => {
    const [records, setRecords] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);
    const [currentPage, setCurrentPage] = useState(1);
    const [totalPages, setTotalPages] = useState(0);
    const [recordType, setRecordType] = useState(-1);
    const [searchTerm, setSearchTerm] = useState("");

    const recordsPerPage = 5;
    const navigate = useNavigate();

    const statusMap = {
        '-1': '待处理',
        '0': '赔付中',
        '1': '已赔付',
        '2': '已拒绝'
    };


    const fetchRecords = async (page: number) => {
        try {
            const response = await axios.get(`/api/v1/insurance/fetch`, {
                params: {
                    page,
                    size: recordsPerPage,
                    searchTerm,
                    filter: recordType
                }
            });

            setRecords(response.data.records);
            setTotalPages(Number(response.data.pagination.totalPages));
        } catch (error) {
            console.error('获取保险记录失败:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleClaim = async (recordId: number, approved: boolean) => {
        try {
            console.log("开始赔付", recordId, approved)
            const response = await axios.post(`/api/v1/insurance/claim`, {
                recordId,
                approved
            });

            if (response.data.success) {
                toast.success("操作成功");
                fetchRecords(currentPage);
            } else {
                toast.error('操作失败');
            }
        } catch (error) {
            toast.error('内部错误');
        }
    };

    const handleRefresh = () => {
        fetchRecords(currentPage);
        toast.success("刷新成功");
    }

    useEffect(() => {
        fetchRecords(currentPage);
    }, [currentPage, recordType]);

    if (loading) return <div>加载中...</div>;

    return (
        <div>
            <h2 className="mb-4 text-xl font-bold">保险赔付管理</h2>

            <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
                <div className="rounded-md border border-gray-200 p-4 shadow-sm">
                    <h3 className="mb-2 text-lg font-medium">待赔付申请</h3>
                    <p className="text-3xl font-bold text-[#673AB7]">
                        {records.filter(r => r.status === -1).length}
                    </p>
                </div>
                <div className="rounded-md border border-gray-200 p-4 shadow-sm">
                    <h3 className="mb-2 text-lg font-medium">已赔付申请</h3>
                    <p className="text-3xl font-bold text-[#673AB7]">
                        {records.filter(r => r.status === 0).length}
                    </p>
                </div>
            </div>

            <div className="my-6 flex items-center justify-between">
                <div className="flex items-center">
                    <div className="relative w-64">
                        <input
                            type="text"
                            placeholder="输入身份证号搜索..."
                            className="w-full rounded-md border border-gray-300 px-4 py-2 pl-10 focus:border-[#673AB7] focus:outline-none"
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            onKeyDown={(e) => e.key === 'Enter' && fetchRecords(1)}
                        />
                    </div>
                    <button
                        onClick={() => fetchRecords(1)}
                        className="ml-2 flex items-center rounded-md bg-[#673AB7] px-4 py-2 text-white hover:bg-[#5E35B1]"
                    >
                        搜索
                    </button>
                </div>
                <button
                    onClick={handleRefresh}
                    className="ml-2 flex items-center rounded-md bg-[#673AB7] px-4 py-2 text-white hover:bg-[#5E35B1]"
                >
                    刷新
                </button>
            </div>

            <div className="mt-6 space-y-6">
                <div className="border-b border-gray-200">
                    <nav className="-mb-px flex space-x-8">
                        <button
                            onClick={() => {
                                setRecordType(-1);
                                setCurrentPage(1);
                            }}
                            className={`whitespace-nowrap border-b-2 px-1 py-4 text-sm font-medium ${recordType === -1 ? 'border-[#673AB7] text-[#673AB7]' : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'}`}
                        >
                            待处理
                        </button>
                        <button
                            onClick={() => {
                                setRecordType(1);
                                setCurrentPage(1);
                            }}
                            className={`whitespace-nowrap border-b-2 px-1 py-4 text-sm font-medium ${recordType === 1 ? 'border-[#673AB7] text-[#673AB7]' : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'}`}
                        >
                            已赔付
                        </button>
                        <button
                            onClick={() => {
                                setRecordType(2);
                                setCurrentPage(1);
                            }}
                            className={`whitespace-nowrap border-b-2 px-1 py-4 text-sm font-medium ${recordType === 2 ? 'border-[#673AB7] text-[#673AB7]' : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700'}`}
                        >
                            已拒绝
                        </button>
                    </nav>
                </div>

                <div className="overflow-hidden rounded-md border border-gray-200 shadow-sm">
                    <table className="min-w-full divide-y divide-gray-200">
                        <thead className="bg-gray-50">
                            <tr>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">姓名</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">身份证号</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">申请日期</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">赔付金额</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">状态</th>
                                <th scope="col" className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">操作</th>
                            </tr>
                        </thead>
                        <tbody className="divide-y divide-gray-200 bg-white">
                            {records.map((record) => (
                                <tr key={record.id}>
                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                        {record.patientName}
                                    </td>
                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                        {record.idNumber}
                                    </td>
                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                        {record.date}
                                    </td>
                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                        {ethers.formatEther(record.applyAmount)} ETH
                                    </td>
                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                        {statusMap[record.status.toString() as keyof typeof statusMap]}
                                    </td>
                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                        {recordType === -1 && (
                                            <div className="flex space-x-2">
                                                <button
                                                    className="rounded-md bg-green-500 px-3 py-1 text-xs text-white hover:bg-green-600"
                                                    onClick={() => handleClaim(record.id, true)}
                                                >
                                                    赔付
                                                </button>
                                                <button
                                                    className="rounded-md bg-red-500 px-3 py-1 text-xs text-white hover:bg-red-600"
                                                    onClick={() => handleClaim(record.id, false)}
                                                >
                                                    拒绝
                                                </button>
                                            </div>
                                        )}
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>

                {totalPages > 1 && (
                    <div className="flex items-center justify-between">
                        <button
                            onClick={() => setCurrentPage(p => Math.max(p - 1, 1))}
                            disabled={currentPage === 1}
                            className="rounded-md border border-gray-300 px-4 py-2 disabled:opacity-50"
                        >
                            上一页
                        </button>
                        <span>
                            第 {currentPage} 页 / 共 {totalPages} 页
                        </span>
                        <button
                            onClick={() => setCurrentPage(p => Math.min(p + 1, totalPages))}
                            disabled={currentPage === totalPages}
                            className="rounded-md border border-gray-300 px-4 py-2 disabled:opacity-50"
                        >
                            下一页
                        </button>
                    </div>
                )}
            </div>
        </div>
    );
};

export default InsuranceManage;